package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.ChinaTotal;
import com.example.entity.LineTrend;
import com.example.entity.NocvData;
import com.example.entity.NocvNews;
import com.example.service.ChinaTotalService;
import com.example.service.IndexService;
import com.example.service.NocvNewsService;
import com.example.utils.FormatDate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class IndexController {

    @Autowired
    private IndexService indexService;

    @Autowired
    private ChinaTotalService chinaTotalService;

    @Autowired
    private NocvNewsService nocvNewsService;


    /**
     * 返回最新一条数据
     * @param
     * @return
     */
    @RequestMapping("/toChina")
    public String toChina(Model model){
        Jedis jedis = new Jedis("localhost");
        if (jedis!=null){
            String confirm = jedis.get("confirm");
            String input = jedis.get("input");
            String heal = jedis.get("heal");
            String dead = jedis.get("dead");
            String updateTime = jedis.get("updateTime");
            if (StringUtils.isNotBlank(confirm)
                    && StringUtils.isNotBlank(input)
                    && StringUtils.isNotBlank(heal)
                    && StringUtils.isNotBlank(dead)
                    && StringUtils.isNotBlank(updateTime)) {
                ChinaTotal chinaTotalRedis = new ChinaTotal();
                chinaTotalRedis.setConfirm(Integer.parseInt(confirm));
                chinaTotalRedis.setInput(Integer.parseInt(input));
                chinaTotalRedis.setHeal(Integer.parseInt(heal));
                chinaTotalRedis.setDead(Integer.parseInt(dead));
                // 格式调整 String ----> Date

                chinaTotalRedis.setUpdateTime(FormatDate.ConvertStringToDate(updateTime));
                System.out.println("redis中的数据：" + chinaTotalRedis);
                model.addAttribute("chinaTotal", chinaTotalRedis);
            }else{
                QueryWrapper<ChinaTotal> queryWrapper=new QueryWrapper<>();
                queryWrapper.orderByDesc("id");
                List<ChinaTotal> list = chinaTotalService.list(queryWrapper);
                ChinaTotal chinaTotal = list.get(0);
                model.addAttribute("chinaTotal",chinaTotal);//扔回前台

                jedis.set("confirm",String.valueOf(chinaTotal.getConfirm()));
                jedis.set("input",String.valueOf(chinaTotal.getInput()));
                jedis.set("heal",String.valueOf(chinaTotal.getHeal()));
                jedis.set("dead",String.valueOf(chinaTotal.getDead()));
                jedis.set("updateTime",String.valueOf(chinaTotal.getUpdateTime()));
            }
        }else{
            QueryWrapper<ChinaTotal> queryWrapper=new QueryWrapper<>();
            queryWrapper.orderByDesc("id");
            List<ChinaTotal> list = chinaTotalService.list(queryWrapper);
            ChinaTotal chinaTotal = list.get(0);
            model.addAttribute("chinaTotal",chinaTotal);//扔回前台
        }
        List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
        model.addAttribute("newsList",newsList);
        return "china";
    }

    /**
     * 绑定echart数据源
     * @return
     */
    @RequestMapping("/query")
    @ResponseBody
    public List<NocvData> queryData() throws ParseException {
        //每天更新一次使用场景
//        QueryWrapper<NocvData> queryWrapper=new QueryWrapper<>();
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        String format1 = format.format(new Date());
//        queryWrapper.ge("update_time", format.parse(format1));
//        List<NocvData> list = indexService.list(queryWrapper);


        Jedis jedis = new Jedis("127.0.0.1");
        if (jedis!=null){

            // 1.1 有缓存数据 返回数据即可
            List<String> listRedis = jedis.lrange("nocvdata", 0 ,33);
            List<NocvData> dataList = new ArrayList<>();
            if (listRedis.size()>0){
                for(int i=0; i<listRedis.size(); i++) {
                    System.out.println("列表项为: "+listRedis.get(i));
                    String s = listRedis.get(i);
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    Object name = jsonObject.get("name");
                    Object value = jsonObject.get("value");
                    NocvData nocvData = new NocvData();
                    nocvData.setName(String.valueOf(name));
                    nocvData.setValue(Integer.parseInt(value.toString()));
                    dataList.add(nocvData);
                }
                // 查询redis缓存数据库 返回的数据
                return dataList;
            }else{
                // 1.2 redis没有数据 查Mysql数据库,更新缓存
                List<NocvData> list = indexService.listOrderByIdLimit34();
                for (NocvData nocvData : list){
                    jedis.lpush("nocvdata", JSONObject.toJSONString(nocvData));
                }
                // 返回的数据中的数据
                return list;
            }
        }

        List<NocvData> list = indexService.listOrderByIdLimit34();
        return list;
    }

    /**
     * 跳转pie页面
     * @return
     */
    @RequestMapping("/toPie")
    public String toPie() {
        return "pie";
    }

    /**
     * 绑定echart饼状图数据源
     * @return
     */
    @RequestMapping("/queryPie")
    @ResponseBody
    public List<NocvData> queryPieData() {
        List<NocvData> list = indexService.listOrderByIdLimit34();
        return list;
    }

    /**
     * 跳转bar页面
     * @return
     */
    @RequestMapping("/toBar")
    public String toBar() {
        return "bar";
    }

    /**
     * 绑定echart饼状图数据源
     * @return
     */
    @RequestMapping("/queryBar")
    @ResponseBody
    public Map<String, List<Object>> queryBarData() {
        //所有城市和数值
        List<NocvData> list = indexService.listOrderByIdLimit34();
        //所有城市
        List<String> cityList = new ArrayList<>();
        for (NocvData data : list) {
            cityList.add(data.getName());
        }
        //所有城市的疫情数值
        List<Integer> dataList = new ArrayList<>();
        for (NocvData data : list) {
            dataList.add(data.getValue());
        }

        //创建map
        Map map = new HashMap();
        map.put("cityList", cityList);
        map.put("dataList", dataList);
        return map;
    }

    /**
     * 跳转line页面
     * @return
     */
    @RequestMapping("/toLine")
    public String toLine() {
        return "line";
    }

    /**
     * 绑定echart折线图数据源
     * @return
     * select * from line_trend order by create_time limit 7;
     */
    @ResponseBody
    @RequestMapping("/queryLine")
    public Map<String ,List<Object>> queryLineData(){
        //近七天所有数据
        List<LineTrend> list7 = indexService.findSevenData();
        //封装所有确诊人数
        List<Integer> confirmList = new ArrayList<>();
        //封装所有隔离人数
        List<Integer> isolationList = new ArrayList<>();
        //封装所有治愈人数
        List<Integer> curemList = new ArrayList<>();
        //封装所有死亡人数
        List<Integer> deadList = new ArrayList<>();
        //封装所有疑似人数
        List<Integer> similarList = new ArrayList<>();

        for (LineTrend data: list7) {
            confirmList.add(data.getConfirm());
            isolationList.add(data.getIsolation());
            curemList.add(data.getCure());
            deadList.add(data.getDead());
            similarList.add(data.getSimilar());
        }

        Map map=new HashMap();
        map.put("confirmList",confirmList);
        map.put("isolationList",isolationList);
        map.put("curemList",curemList);
        map.put("deadList",deadList);
        map.put("similarList",similarList);

        return map;
    }


}
